package com.example.message.controller;

import com.example.message.utils.Md5Utils;
import com.example.message.pojo.User;
import com.example.message.pojo.UserInfo;
import com.example.message.response.Response;
import com.example.message.response.ResponseCodeEnum;
import com.example.message.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/login")
    public Response index (String userName, String password, HttpServletRequest request){
        User user = userService.Login(userName, password);
        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
        }
        return new Response().success(user);
    }

    @PostMapping("/register")
    public Response register(@RequestBody User user) {
        List<User> list = userService.selectByUserName(user.getUserName());
        if (list.size() > 0) {
            return new Response(ResponseCodeEnum.FAILURE.code(), "用户名重复", false);
        }
        String password = Md5Utils.getMd5Password(user.getPassword());
        user.setPassword(password);
        return new Response().success(userService.register(user));
    }

    @PostMapping("/updatePassword")
    public Response updatePassword(String oldPassword, String newPassword, HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        if (user == null) {
            return new Response().setResponseCode(ResponseCodeEnum.USER_NOT_LOGGED_IN);
        }
        if (Md5Utils.getMd5Password(oldPassword).equals(user.getPassword())){
           boolean b =  userService.updatePassword(user.getId(),newPassword);
           return new Response().success();
        } else {
            return new Response().setResponseCode(ResponseCodeEnum.USER_LOGIN_ERROR);
        }
    }

    @PostMapping("/updateMessage")
    public  Response updateMessage(UserInfo userInfo, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User loginUser = (User)session.getAttribute("user");
        if (loginUser == null) {
            return new Response().setResponseCode(ResponseCodeEnum.USER_PASSWORD_ERROR);
        }
        boolean b = userService.updateMessage(userInfo);
        return new Response().success();
    }

}
